﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace FastReplace
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private bool Cancel = false;

        private void button2_Click(object sender, EventArgs e)
        {
            string file = textBox1.Text;
            string from = textBox2.Text;
            string to = textBox3.Text;

            if (string.IsNullOrEmpty(file))
            {
                MessageBox.Show("Por favor, selecione um arquivo");
            }
            else if (File.Exists(file) == false)
            {
                MessageBox.Show("O arquivo especificado é inválido ou não existe");
            }
            else if (string.IsNullOrEmpty(from))
            {
                MessageBox.Show("Por favor, especifique o texto a ser substituído");
                textBox2.Focus();
            }
            else
            {
                from = from.Replace("\\t", "\t").Replace("\\n", "\n").Replace("\\r", "\r");
                to = to.Replace("\\t", "\t").Replace("\\n", "\n").Replace("\\r", "\r");

                textBox1.Enabled = false;
                textBox2.Enabled = false;
                textBox3.Enabled = false;
                button1.Enabled = false;
                button2.Enabled = false;
                button3.Visible = true;
                button4.Visible = false;
                progressBar1.Visible = true;
                progressBar1.Value = 0;

                FileInfo fi = new FileInfo(file);
                string output = fi.DirectoryName + "\\output.txt";

                try
                {
                    this.Cursor = Cursors.WaitCursor;
                    Application.DoEvents();

                    long count = 0;

                    Cancel = false;

                    using (StreamReader sr = new StreamReader(file, true))
                    using (StreamWriter sw = new StreamWriter(output, false, sr.CurrentEncoding))
                    {
                        while (sr.EndOfStream == false)
                        {
                            if (Cancel)
                                throw new Exception();

                            string line = sr.ReadLine();
                            string newLine = line.Replace(from, to);

                            if (string.Compare(line, newLine) != 0)
                                count++;

                            sw.WriteLine(newLine);

                            int newValue = (int)(sr.BaseStream.Position * 100d / sr.BaseStream.Length);
                            if (progressBar1.Value != newValue)
                            {
                                progressBar1.Value = newValue;
                                Application.DoEvents();
                            }
                        }
                    }

                    progressBar1.Value = 100;

                    if (count > 0)
                    {
                        File.Replace(output, file, null);
                    }

                    MessageBox.Show("Foram feitas " + count.ToString() + " substituições!");
                }
                catch (Exception exception)
                {
                    if (Cancel == false)
                    {
                        MessageBox.Show("Erro ao processar: " + exception.Message);
                    }
                }

                if (File.Exists(output))
                {
                    try
                    {
                        File.Delete(output);
                    }
                    catch { }
                }

                this.Cursor = Cursors.Default;
                textBox1.Enabled = true;
                textBox2.Enabled = true;
                textBox3.Enabled = true;
                button1.Enabled = true;
                button2.Enabled = true;
                button3.Visible = false;
                button4.Visible = true;
                progressBar1.Visible = false;
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog(this) == DialogResult.OK)
            {
                textBox1.Text = openFileDialog1.FileName;
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            Cancel = true;
        }

        private void button4_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}
